package com.stt.weather.design.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.stt.weather.design.factory.NotificationFactory;
import com.stt.weather.model.WeatherData;
import com.stt.weather.design.observer.WeatherObserver;
import com.stt.weather.util.CityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.HashSet;

/**
 * 天气服务类
 * 负责获取天气数据和通知观察者
 */
@Service
public class DesignWeatherService {
    
    @Autowired
    private NotificationFactory notificationFactory;
    
    // 存储启用的通知类型
    private Set<String> enabledNotificationTypes = new HashSet<>();
    
    /**
     * 启用指定类型的通知
     * @param type 通知类型
     */
    public void enableNotification(String type) {
        enabledNotificationTypes.add(type);
    }
    
    /**
     * 禁用指定类型的通知
     * @param type 通知类型
     */
    public void disableNotification(String type) {
        enabledNotificationTypes.remove(type);
    }
    
    /**
     * 获取天气数据并通知观察者
     */
    public WeatherData getWeatherData(String cityCode) {
        WeatherData weatherData = fetchWeatherData(cityCode);
        notifyObservers(weatherData);
        return weatherData;
    }
    
    /**
     * 模拟获取天气数据
     */
    private WeatherData fetchWeatherData(String cityCode) {
        // 实时天气查询
        String key = "b48ff5173c4e49d789d930dbfcab9419";
        String url = "https://devapi.qweather.com/v7/weather/now?location="
                + cityCode + "&key=" + key;
        String response = HttpUtil.createGet(url).execute().body();
        if(StrUtil.isNotEmpty(response)) {
            String code = JSONUtil.parseObj(response).getStr("code");
            if("200".equals(code)) {
                String data = JSONUtil.parseObj(response).getStr("now");
                WeatherData weatherData = JSONUtil.toBean(data, WeatherData.class);
                // 设置城市名称和编码
                weatherData.setCityCode(cityCode);
                weatherData.setCityName(CityUtil.getCityName(cityCode));
                return weatherData;
            }
        }
        return null;
    }
    
    /**
     * 通知所有启用的观察者
     */
    private void notifyObservers(WeatherData weatherData) {
        for (WeatherObserver observer : notificationFactory.getAllObservers()) {
            if (enabledNotificationTypes.contains(observer.getType())) {
                observer.update(weatherData);
            }
        }
    }
} 